package
{
      import com.pblabs.engine.components.TickedComponent;
      import com.pblabs.engine.entity.PropertyReference;

      import flash.events.Event;

      public class ColorModifierComponent extends TickedComponent
      {
            // A reference to the position property of another Component
            public var colorReference:PropertyReference;
            // Set to true when this component should change the color
            // of an Entity
            protected var run:Boolean = true;

            public function ColorModifierComponent()
            {
            }

            // Called when a Component is added to an Entity
            protected override function onAdd():void
            {
                  super.onAdd();
                  // Call the onGoEvent() and onStopEvent() functions
                  // in response to the "Go" and "Stop" events
                  owner.eventDispatcher.addEventListener(
                        "Go", onGoEvent);
                  owner.eventDispatcher.addEventListener(
                        "Stop", onStopEvent);
            }

            // Called when a Component is removed from an Entity
            protected override function onRemove():void
            {
                  super.onRemove();
                  // Remove the event listeners added in the onAdd()
                  // function
                  owner.eventDispatcher.removeEventListener(
                        "Go", onGoEvent);
                  owner.eventDispatcher.removeEventListener(
                        "Stop", onStopEvent);
            }

            private function onStopEvent(event:Event):void
            {
                  // Stop this component from modifying the owner Entity's
                  // color
                  run = false;
            }

            private function onGoEvent(event:Event):void
            {
                  // Allow this component to modify the owner Entity's
                  // color
                  run = true;
            }

            // The onTick() function is called once per frame
            public override function onTick(tickRate:Number):void
            {
                  if (run)
                  {
                        // Generate a random color
                        var newColor:uint = Math.random()*uint.MAX_VALUE;

                        // Set the  position of the external Component
                        owner.setProperty(colorReference, newColor);
                  }
            }
      }
}